package edu.chl.food_store.beans.control;

import edu.chl.food_store.beans.backing.*;
import edu.chl.food_store.beans.ejb.ProductEJB;
import edu.chl.food_store.entities.Product;
import java.io.Serializable;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;

/**
 * ProdutControllerBean:
 * Controller bean for handling product operations (listing/adding/removing). 
 */
@ManagedBean
@RequestScoped
public class ProductControllerBean implements Serializable {

    @EJB
    private ProductEJB productEjb;
    @ManagedProperty(value = "#{addProductBackingBean}")
    AddProductBackingBean productData;

    public List<Product> getProducts() {
        return productEjb.findProducts();
    }

    public void addProduct() {
        String name = productData.getName();
        String cat = productData.getCategory();
        String desc = productData.getDescription();
        double price = productData.getPrice();
        Product product = new Product(name, cat, desc, price);
        productEjb.createProduct(product);
    }

    public void deleteProduct(Product product) {
        Map<String, Object> requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
        ProductBackingBean products = (ProductBackingBean)requestMap.get("productBackingBean");
        products.getProducts().remove(product);
        productEjb.destroyProduct(product);
    }

    public AddProductBackingBean getProductData() {
        return productData;
    }

    public void setProductData(AddProductBackingBean productData) {
        this.productData = productData;
    }
}
